import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:flutter/services.dart';

class FlutterAtauth {
  static const MethodChannel _channel =
      const MethodChannel('flutter_atauth');

  static Future<String> getLoginToken({
    String appKey, 
    int timeout
  }) async {
    Completer<String> completer = Completer<String>();
    await _channel.invokeMethod('getLoginToken', <String, dynamic>{
      "timeout": timeout ?? 60000,
      "appKey": appKey,
    });
    BasicMessageChannel _platform = BasicMessageChannel("flutter_atauth_platform", StringCodec());
    Future<dynamic> handler(dynamic message) async {
      if(!completer.isCompleted) {
        if(message == null) {
          completer.completeError("");
          return;
        } 

        dynamic tokenRet = JsonDecoder().convert(message);
        if(tokenRet == null) {
          completer.completeError("未知错误");
          return;
        }

        print(tokenRet);

        if(Platform.isAndroid) {
          if(tokenRet["code"] == "6000")  {
            /// 拉去授权页面成功，啥都不做
          } else if(tokenRet["code"] == "8000") {
            /// 获取到token
            completer.complete(tokenRet["token"]);
            _platform.setMessageHandler(null);
          } else {
            completer.completeError(tokenRet["msg"]);
          }
        }

        if(Platform.isIOS) {
          if(
            tokenRet["resultCode"] == "600001"  /// 拉去授权页面成功，啥都不做
            || tokenRet["resultCode"] == "700002" /// 点击登录按钮事件
            || tokenRet["resultCode"] == "700003" /// 点击check box事件
            || tokenRet["resultCode"] == "700004" /// 点击协议富文本文字事件
          )  {
           
          } else if(tokenRet["resultCode"] == "600000") {
            /// 获取到token
            completer.complete(tokenRet["token"]);
            _platform.setMessageHandler(null);
          } else {
            completer.completeError(tokenRet["msg"]);
            _platform.setMessageHandler(null);
          }
        }
      }
    }
    _platform.setMessageHandler(handler);
    return completer.future;
  }
}
